package com.dhl.springbootrabbitmq.controller;

import com.dhl.springbootrabbitmq.config.DelayedTtlQueueConfig;
import com.dhl.springbootrabbitmq.config.TtlQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Action;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Locale;

/**
 * @author danghailiang
 */
@Slf4j
@RequestMapping("/ttl")
@RestController
public class SendMsgController {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/send/{message}")
    public void sendMessage(@PathVariable String message){
        log.info("接收到的数据是：{},将要转发给队列！！！！",message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE,TtlQueueConfig.ROUTING_XA,message.getBytes(StandardCharsets.UTF_8));
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE,TtlQueueConfig.ROUTING_XB,message.getBytes(StandardCharsets.UTF_8));
    }

    @GetMapping("/sendMsg/{msg}/{ttl}")
    public void sendMessage(@PathVariable("msg") String message, @PathVariable("ttl") String ttl){
        log.info("接收到的时间是：{}，设置的过期时间是：{}，数据是：{},将要转发给队列！！！！",new Date(),ttl, message);
        rabbitTemplate.convertAndSend(TtlQueueConfig.X_CHANGE,TtlQueueConfig.ROUTING_XA,message.getBytes(StandardCharsets.UTF_8),msg -> {
            msg.getMessageProperties().setExpiration(ttl);
            return msg;
        });
    }

    @GetMapping("sendDelayedMsg/{message}/{delayedTTL}")
    public void sendMessage(@PathVariable("message") String message,@PathVariable("delayedTTL") Integer delayedTTL){
        log.info("接收到的时间是：{}，设置的过期时间是：{}，数据是：{},将要转发给队列！！！！",new Date(),delayedTTL, message);
        rabbitTemplate.convertAndSend(DelayedTtlQueueConfig.DELAYED_EXCHANGE,DelayedTtlQueueConfig.DELAYED_ROUTING_KEY,message.getBytes(StandardCharsets.UTF_8), msg -> {
            msg.getMessageProperties().setDelay(delayedTTL);
//            msg.getMessageProperties().setHeader("x-delay", delayedTTL);
            return msg;
        });
    }

}
